const Koa = require('koa');
const fs = require('fs');
const path = require('path');
const koaForm = require("formidable-upload-koa");
const router = require('koa-router')();
const app = new Koa();

const options = {
	uploadDir: `${__dirname}/imgs/`,
	keepExtensions: true,
	multiples :true,// 需html5支持
	singleFileMaxSize: 2 * 1024 * 1024 //2M 修改源码添加的
};

// add url-route:
router.get('/', async ctx => {
    ctx.type = 'html';
    ctx.body = fs.createReadStream('./upload_imgs.html');
});

router.get('/imgs',async ctx => {
	let files = [];
	try{
		files = await new Promise((resolve,reject) =>
			fs.readdir(options.uploadDir,(err,files) => 
				err?reject(err):resolve(files))
		);
	}catch(err){
		console.log(err);
	}finally{
		ctx.response.set('Content-Type','application/json');
		ctx.body = files;
	}

});

router.post('/upload_imgs',async ctx => {
	let filesName = [];

	//ctx.req.koaFormError = true || undefined 修改源码添加
	if(!ctx.req.koaFormError){
		let files = ctx.req.files.test;
		let fileIsImg = file => file.type.indexOf('image') > -1?
								true:
								fs.unlinkSync(file.path);
		//上传单个文件是对象，多个文件是数组，里面是对象
		if(Array.isArray(files)){
			for(let x of files){
				fileIsImg(x)?filesName.push(path.basename(x.path)):null;
			}
		}else{
			fileIsImg(files)?filesName.push(path.basename(files.path)):null;
		}
	}else{
		console.log('file is to big');
	}
	
	ctx.response.set('Content-Type','application/json');
	ctx.body = filesName;
});

// add router middleware:

app.use(async (ctx,next) => {
    console.log(`${ctx.request.method} ${ctx.request.url}`);
	await next();
});

app.use(koaForm(options));

app.use(router.routes());


app.listen(3000);
